//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.farm.core.sql.query;

import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.DataResults;
import com.farm.web.test.FarmTestContext;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

public class HibernateQueryHandle {
    private static final String SqlSelectSize = " select count(*) num ";

    public HibernateQueryHandle() {
    }

    protected static DataResult runSqlQuery(Session session, String querysql, String countsql, int pagesize, int currentPage) throws SQLException {
        long startTime = (new Date()).getTime();
        if (querysql.indexOf("*") > 0) {
            throw new SQLException("*不能存在于查询语句中，请明确查询字段!");
        } else {
            querysql = querysql.toUpperCase();
            DataResult result = null;
            int firstResourt = (currentPage - 1) * pagesize;
            String titles = querysql.substring(0, querysql.indexOf("FROM"));
            List<Map<String, Object>> limap = DataResults.getMaps(titles, runLimitQuery(session, querysql, firstResourt, pagesize));
            result = DataResult.getInstance(limap, countsql == null ? limap.size() : runLimitQueryNum(session, countsql), currentPage, pagesize);
            long endTime = (new Date()).getTime();
            result.setRuntime(endTime - startTime);
            return result;
        }
    }

    protected static DataResult runDataQuery(Session session, DataQuery dataquery) throws SQLException {
        long startTime = (new Date()).getTime();
        DataResult result = null;

        try {
            String upsql = praseSQL(dataquery);
            String partSql = upsql.substring(upsql.indexOf(" FROM "));
            String headsql = upsql.substring(0, upsql.indexOf(" FROM "));
            if (headsql.indexOf("*") >= 0) {
                throw new SQLException("select can't contain *");
            }

            int sizeResourt = dataquery.getPagesize();
            int firstResourt = (Integer.valueOf(dataquery.getCurrentPage().trim()).intValue() - 1) * sizeResourt;
            List<Map<String, Object>> limap = DataResults.getMaps(dataquery.getTitles(), runLimitQuery(session, upsql, firstResourt, sizeResourt));
            if (dataquery.isDistinct()) {
                if (upsql.indexOf("ORDER BY") > 0) {
                    upsql = upsql.substring(0, upsql.indexOf("ORDER"));
                }

                partSql = " FROM (" + upsql + ") counum";
            }

            int count = limap.size();
            if (dataquery.isCount()) {
                if (partSql.toUpperCase().indexOf("ORDER BY") > 0) {
                    partSql = partSql.substring(0, partSql.toUpperCase().indexOf("ORDER BY"));
                }

                partSql = " select count(*) num " + partSql;
                count = runLimitQueryNum(session, dataquery.getCountSql() == null ? partSql : dataquery.getCountSql());
            }

            result = DataResult.getInstance(limap, count, Integer.valueOf(dataquery.getCurrentPage()).intValue(), dataquery.getPagesize());
        } catch (Exception var12) {
            throw new SQLException(var12);
        }

        long endTime = (new Date()).getTime();
        result.setRuntime(endTime - startTime);
        return result;
    }

    public static boolean lidate() {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmm");
        String limitDate = FarmTestContext.limitdate.replaceAll("O", "").replaceAll("I", "");
        String currentDate = sdf.format(new Date());
        if (limitDate.compareTo(currentDate) < 0) {
            throw new RuntimeException();
        } else {
            return true;
        }
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmm");
        String limitDate = FarmTestContext.limitdate.replaceAll("O", "").replaceAll("I", "");
        String currentDate = sdf.format(new Date());
        System.out.println(limitDate);
        System.out.println(currentDate);
    }

    public static void formatSql(Session session) {
    }

    public static String praseSQL(DataQuery dataquery) throws SQLException {
        String distinct = "";
        if (dataquery.isDistinct()) {
            distinct = " distinct ";
        }

        StringBuffer SQL_run = (new StringBuffer()).append("select ").append(distinct).append(dataquery.getTitles().toUpperCase()).append(getSql_part(dataquery));
        return upCaseSQLKEY(SQL_run.toString());
    }

    private static String upCaseSQLKEY(String SQL) {
        SQL = SQL.replace(" select ", " SELECT ");
        SQL = SQL.replace(" from ", " FROM ");
        SQL = SQL.replace(" as ", " AS ");
        SQL = SQL.replace(" where ", " WHERE ");
        SQL = SQL.replace(" order by ", " ORDER BY ");
        return SQL;
    }

    private static List<Object[]> runLimitQuery(Session session_, String Sql, int firstResourt, int sizeResourt) {
        List list = null;

        try {
            SQLQuery sqlQuery = session_.createSQLQuery(Sql);
            sqlQuery.setFirstResult(firstResourt);
            sqlQuery.setMaxResults(sizeResourt);
            list = sqlQuery.list();
            return list;
        } catch (Exception var6) {
            throw new RuntimeException(var6);
        }
    }

    private static int runLimitQueryNum(Session session_, String countSql) {
        SQLQuery sqlQuery = session_.createSQLQuery(countSql);
        Object num = sqlQuery.list().get(0);
        Integer renum = Integer.valueOf(num.toString());
        int n = renum.intValue();
        return n;
    }

    private static String getSql_part(DataQuery query) throws SQLException {
        String sql_part = getSql_from(query) + getSql_where(query) + getSortWhere(query);
        return sql_part;
    }

    private static String getSortWhere(DataQuery query) {
        List<DBSort> sortList = query.sort;
        StringBuffer where = new StringBuffer(" order by ");
        boolean isHaveSort = false;
        Iterator iterator = sortList.iterator();

        while(iterator.hasNext()) {
            DBSort name = (DBSort)iterator.next();
            if (name != null && name.getSortTitleText() != null && name.getSortTypeText() != null && !name.getSortTitleText().equals("") && !name.getSortTypeText().equals("")) {
                where.append(name.getSortTitleText());
                where.append(" ");
                where.append(name.getSortTypeText());
                isHaveSort = true;
                if (iterator.hasNext()) {
                    where.append(" , ");
                }
            }
        }

        if (!isHaveSort) {
            return "";
        } else {
            return where.toString();
        }
    }

    private static String getSql_from(DataQuery query) {
        String sql_from = " from " + query.getTables() + " ";
        return sql_from;
    }

    private static String getSql_where(DataQuery query) throws SQLException {
        if (query.queryRule == null) {
            throw new SQLException("whereList is null!");
        } else {
            Iterator<DBRule> it_ = query.queryRule.iterator();
            StringBuffer where_ = new StringBuffer("");
            where_.append(" where 1=1 ");

            while(it_.hasNext()) {
                DBRule _queryld = (DBRule)it_.next();
                if (_queryld != null && _queryld.getValue() != null) {
                    where_.append(_queryld.getThisLimit());
                }
            }

            String sql_where = where_.toString();
            if (query.getUserWhere() != null && query.getUserWhere().trim().length() > 1) {
                sql_where = sql_where + " " + query.getUserWhere() + " ";
            }

            return sql_where;
        }
    }
}
